package com.dsl.dslsuzhou.service;

import com.dsl.dslsuzhou.config.CameraConfig;
import com.dsl.dslsuzhou.model.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 摄像头业务服务
 */
@Slf4j
@Service
public class CameraService {
    
    @Autowired
    private CameraThirdPartyService thirdPartyService;
    
    @Autowired
    private CameraConfig cameraConfig;
    
    /**
     * 分页查询摄像头
     */
    public Mono<CameraPageResponse> getCameraPage(CameraPageRequest request, String token) {
        // 参数校验和归一化
        validateAndNormalizePageRequest(request);

        return thirdPartyService.getCameraPage(
                request.getCurrent(),
                request.getSize(),
                request.getDevIds(),
                request.getStatus(),
                token
        );
    }
    
    /**
     * 统计摄像头数量
     */
    public Mono<CameraCountResponse> getCameraCount(CameraCountRequest request, String token) {
        // 参数校验和归一化
        validateAndNormalizeCountRequest(request);

        List<String> devIds = request.getDevIds();
        if (CollectionUtils.isEmpty(devIds)) {
            // 如果没有指定devIds，直接调用一次获取总数
            return thirdPartyService.getCameraPage(1, 1, null, request.getStatus(), token)
                    .map(response -> new CameraCountResponse(response.getTotal()));
        }

        // 按批次切片处理
        int batchSize = cameraConfig.getCount().getBatchSize();
        List<List<String>> batches = splitIntoBatches(devIds, batchSize);

        log.info("摄像头计数查询: 总设备数={}, 批次数={}, 状态过滤={}",
                devIds.size(), batches.size(), request.getStatus());

        // 并行处理所有批次
        return Flux.fromIterable(batches)
                .flatMap(batch -> thirdPartyService.getCameraPage(1, 1, batch, request.getStatus(), token))
                .map(CameraPageResponse::getTotal)
                .reduce(0L, Long::sum)
                .map(CameraCountResponse::new);
    }
    
    /**
     * 校验和归一化分页请求参数
     */
    private void validateAndNormalizePageRequest(CameraPageRequest request) {
        // 归一化devIds
        request.setDevIds(normalizeDevIds(request.getDevIds()));
        
        // 校验devIds数量
        if (request.getDevIds() != null && request.getDevIds().size() > cameraConfig.getValidation().getMaxDevIds()) {
            throw new IllegalArgumentException("devIds数量超过限制，最大支持" + cameraConfig.getValidation().getMaxDevIds() + "个");
        }
        
        // 校验和修正分页参数
        if (request.getCurrent() == null || request.getCurrent() < 1) {
            request.setCurrent(cameraConfig.getValidation().getDefaultCurrent());
        }
        
        if (request.getSize() == null || request.getSize() < 1) {
            request.setSize(cameraConfig.getValidation().getDefaultSize());
        } else if (request.getSize() > cameraConfig.getValidation().getMaxSize()) {
            request.setSize(cameraConfig.getValidation().getMaxSize());
        }
    }
    
    /**
     * 校验和归一化计数请求参数
     */
    private void validateAndNormalizeCountRequest(CameraCountRequest request) {
        // 归一化devIds
        request.setDevIds(normalizeDevIds(request.getDevIds()));
        
        // 校验devIds数量
        if (request.getDevIds() != null && request.getDevIds().size() > cameraConfig.getValidation().getMaxDevIds()) {
            throw new IllegalArgumentException("devIds数量超过限制，最大支持" + cameraConfig.getValidation().getMaxDevIds() + "个");
        }
    }
    
    /**
     * 归一化devIds参数
     * 支持两种传法：多值和逗号分隔，统一归一为去重、去空的列表
     */
    private List<String> normalizeDevIds(List<String> devIds) {
        if (CollectionUtils.isEmpty(devIds)) {
            return null;
        }
        
        return devIds.stream()
                .filter(StringUtils::hasText)  // 去空
                .flatMap(devId -> {
                    // 处理逗号分隔的情况
                    if (devId.contains(",")) {
                        String[] parts = devId.split(",");
                        List<String> partsList = new ArrayList<>();
                        for (String part : parts) {
                            String trimmed = part.trim();
                            if (StringUtils.hasText(trimmed)) {
                                partsList.add(trimmed);
                            }
                        }
                        return partsList.stream();
                    } else {
                        String trimmed = devId.trim();
                        List<String> singleList = new ArrayList<>();
                        singleList.add(trimmed);
                        return singleList.stream();
                    }
                })
                .distinct()  // 去重
                .collect(Collectors.toList());
    }
    
    /**
     * 将列表按指定大小切分为批次
     */
    private <T> List<List<T>> splitIntoBatches(List<T> list, int batchSize) {
        List<List<T>> batches = new ArrayList<>();
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            batches.add(list.subList(i, end));
        }
        return batches;
    }
}
